package com.helpustotravel.core;

import java.io.IOException;
import java.util.Enumeration;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helpustotravel.model.dao.TacheDAO;
import com.helpustotravel.model.jdo.Tache;

public class ServletBase extends HttpServlet {

	private static final long serialVersionUID = 5807326010149075672L;

	protected PersistenceManager pm;
	
	protected String adresseIp;
	
	protected String browserInfos;
	
	protected String language;
	
	protected String charset;
	
	protected String fileUploadArguments = "";
	
	protected Tache tache;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doGet(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("iso-8859-1");
		
		pm = PMF.get().getPersistenceManager();
		
		adresseIp = req.getRemoteAddr();
		browserInfos = req.getHeader("User-Agent");
		language = req.getHeader("Accept-Language");
		charset = req.getHeader("Accept-Charset");
		
		tache = new Tache();
		tache.setAdresseIp(adresseIp);
		tache.setNomTache(getServletName());
		
		String arguments = "";
		Enumeration<String> parameterNames = (Enumeration<String>)req.getParameterNames();
		while(parameterNames.hasMoreElements()) {
			if(arguments.length() > 0) {
				arguments += ", ";
			}
			String parameterName = parameterNames.nextElement();
			if(!parameterName.equals("time")) {
				arguments += parameterName + " : " + req.getParameter(parameterName);
			} 
		}
		
		if(getServletName().equals("Vue")) {
			arguments = "Browser: " + browserInfos + ", Language: " + language + ", Charset: " + charset;
		}
		
		tache.setArguments(arguments);
		
		TacheDAO tacheDao = new TacheDAO(pm);
		tacheDao.insertTache(tache);
		
		resp = doTache(req, resp);
		
		if(fileUploadArguments != "") {
			tache.setArguments(fileUploadArguments);
			tacheDao.insertTache(tache);
		}

		pm.close();
	}
	
	protected HttpServletResponse doTache(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		return resp;
	}
}
